<?php
namespace plugins\goods\controller;

use cmf\controller\ApiPluginBaseController; //引用插件基类
use plugins\goods\model\GoodsCommentModel;
use plugins\order\model\OrderLogModel;
use think\Db;

class ApiGoodsCommentController extends ApiPluginBaseController
{
    protected $uid = '';
    protected $model;
    /**
     * 初始化
     */
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new GoodsCommentModel;
        $this->uid   = $this->getIdentity()->uid;
    }
    /**
     *用户评论
     * @param  $gid        商品id
     * @param  $uid        用户id
     * @param  $oid        订单id
     * @param  $comment    评论内容
     * @param  $img        评论图片
     * @param  $anonym     是否匿名 1是 否unll
     */
    public function comment()
    {
        $param = $this->request->post();
        $param = autoHtmlspecialcharsDecode($param); //参数解码
        checkParam(['gid', 'oid', 'comment', 'score'], $param);
        $gid     = explode(',', $param['gid']); //商品id



        $oid     = $param['oid']; //订单编号
        $comment = json_decode($param['comment'], JSON_UNESCAPED_UNICODE); //评论内容
        if (!is_array($comment)) {
            $comment = [];
        }
        $score = explode(',', $param['score']);
        $uid   = $this->uid;
        $img   = [];
        if (!empty($param['img'])) {
            $img = json_decode($param['img'], JSON_UNESCAPED_UNICODE);
            if (!is_array($img)) {
                $img = [];
            }
        }
        //获取用户信息
        $user = db('member')->where('uid', $uid)->field('nick_name,head_portrait')->find();
        if (!$user) {
            return api_json_echo(false, '该用户不存在', '', 101);
        }
        $add = [];
        foreach ($gid as $key => $value) {
            $goods = db('goods')->where('id', $value)->find();
            //获取订单商品信息
            $order = db('order_goods_list')->where(['order_goods_id' => $value, 'order_num' => $oid])->find();
            if (!$order) {
                return api_json_echo(false, '该订单商品不存在', '', 102);
            }
            if (!empty($param['anonym']) && $param['anonym'] == 1) {
                $add['is_anonym'] = 1;
            }
            if (isset($img[$key])) {
                $add['img'] = [];
                foreach ($img[$key] as $imgk => $imgv) {
                    $data = $this->saveBase64Image('comment', 'commentimg', $imgv);
                    if ($data['code'] == 0) {
                        $add['img'][$imgk] = $data['url'];
                    }
                }
                $add['img'] = json_encode($add['img'], JSON_UNESCAPED_UNICODE);
            }
            $head = 'plugins' . DS . 'goods' . DS . 'view' . DS . 'public' . DS . 'image' . DS . 'head.png';
            $add['uid']      = $uid;
            $add['goods_id'] = $value;
            $add['store_id'] = !empty($goods['store_id']) ? $goods['store_id'] : '';
            $add['store_name'] = !empty($goods['store_name']) ? $goods['store_name'] : '';
            $add['order_id']      = $oid;
            $add['nick_name']     = $user['nick_name']; //用户名
            $add['head_portrait'] = !empty($user['head_portrait'])?$user['head_portrait']:$head; //用户头像
            $add['goods_name']    = $order['order_goods_name']; //商品名
            $add['goods_img']     = $order['order_goods_img']; //商品图
            $add['price']         = $order['order_goods_price']; //商品价格
            $add['goods_spec']    = $order['order_goods_spec']; //规格
            $add['comment']       = isset($comment[$key]) ? $comment[$key] : '';
            $add['score']         = isset($score[$key]) ? $score[$key] : '5'; //评分, 默认五分好评
            $add['add_time']      = time();

            $result               = $this->model->insertGetId($add);
            $comment_id           = $result;
            db('order_goods_list')->where(['order_goods_id' => $value, 'order_num' => $oid])->update(['comment_id' => $comment_id]); //给订单标记以评论
            $olm       = new OrderLogModel();
            $createLog = $olm->createLog(14, $oid, $order['order_goods_name'], 1);
        }

        db('order')->where('order_num', $oid)->update(['order_status' => 10]);

        return api_json_echo(true, '评论成功！', null, 200);
    }
    /**
     * 用户回复评论
     * @param  $cid        评论id
     * @param  $uid        用户id
     * @param  $comment    评论内容
     */
    public function reply()
    {
        $param  = $this->request->post();
        $uid    = $this->uid;
        $member = db('member')->where('uid', $uid)->find();
        if (!$member) {
            return api_json_echo(false, '用户不存在', '', 100);
        }
        $add = [
            'cid'           => $param['cid'],
            'uid'           => $uid,
            'nick_name'     => $member['nick_name'],
            'head_portrait' => $member['head_portrait'],
            'comment'       => $param['comment'],
            'add_time'      => time(),
            'reply_type'    => 1, //用户回复
        ];
        //查头像昵称
        $data = db('goods_comment_reply')->insert($add);
        db('goods_comment')->where('id', $param['cid'])->setInc('reply');
        if (!$data) {
            return api_json_echo(false, '回复失败', '', 101);
        }
        return api_json_echo(true, '回复成功', '', 200);
    }
    /**
     * 评论列表
     * @param  $gid        商品id
     * @param  $sort       排序 1默认2时间
     */
    public function commentList()
    {
        $param = $this->request->post();
        checkParam(['gid', 'pageNum', 'page', 'type'], $param);
        //1好评率2好评，中评，差评搜索加数量 3评论总数，4.评论第一条好评
        $where = "goods_id=" . $param['gid'];
        $order = "sort asc,add_time desc";
        // if (!empty($param['sort']) && $param['sort'] = 2) {
        //     $order = "add_time desc";
        // }
        $type_num = [
            'all_num'   => 0, //全部数量
            'very_good' => 0, //好评数
            'general'   => 0, //中评数
            'rubbish'   => 0, //差评数
        ];
        $search = 1;
        //评论类型
        switch ($param['type']) {
            case 'all': //全部评论
                break;
            case '1': //好评
                $search .= " and score in (4,5)";
                break;
            case '2': //中评
                $search .= " and score = 3";
                break;
            case '3': //差评
                $search .= " and score in (1,2)";
                break;
            default:
                return api_json_echo(false, '类型错误', null, 101);
                break;
        }
        $type_num['very_good'] = $this->model->where($where)->where('score', 'in', [4, 5])->count();
        $type_num['general']   = $this->model->where($where)->where('score', 3)->count();
        $type_num['rubbish']   = $this->model->where($where)->where('score', 'in', [1, 2])->count();
        $type_num['all_num']   = $type_num['very_good'] + $type_num['general'] + $type_num['rubbish'];
        //好评率
        @$goods_ratio = $type_num['very_good'] / $type_num['all_num'];
        $goods_ratio = ((number_format($goods_ratio, 2)) * 100) . "%"; //保留两位小数

        $data        = $this->model
            ->where($where)->where($search)->order($order)
            ->field('id,uid,score,comment,img,goods_img,add_time,nick_name,head_portrait,goods_spec,reply,is_anonym')
            ->paginate($param['pageNum'], false, ['page' => $param['page']])
            ->each(function ($item) {
                $trans                 = $this->transform($item);
                $item['img']           = $trans['img'];
                $item['add_time']      = $trans['add_time'];
                $item['goods_img']     = $trans['goods_img'];
                $item['nick_name']     = $trans['nick_name'];
                $item['head_portrait'] = $trans['head_portrait'];
                //查询店家回复
                $reply = db('goods_comment_reply')->where(['cid' => $item['id'], 'reply_type' => 2])->field('comment,add_time')->select();
                if ($reply) {
                    $item['store_reply'] = $reply;
                }
                return $item;
            })->toArray();
        $data['type_num']    = $type_num; //商品类型数量
        $data['goods_ratio'] = $goods_ratio; //好评率
        return api_json_echo(true, '成功', $data, 200);
    }
    /**
     * 获取最新好评
     */
    public function getCommentFirst()
    {
        $param = $this->request->post();
        checkParam(['gid'], $param);
        $where = "goods_id=" . $param['gid'];
        //按照评分排序
        $list     = $this->model->where($where)->order('add_time', 'desc')->order('score', 'desc')->find();
        $type_num = [
            'all_num'   => 0, //全部数量
            'very_good' => 0, //好评数
            'general'   => 0, //中评数
            'rubbish'   => 0, //差评数
        ];
        $type_num['very_good'] = $this->model->where($where)->where('score', 'in', [4, 5])->count();
        $type_num['general']   = $this->model->where($where)->where('score', 3)->count();
        $type_num['rubbish']   = $this->model->where($where)->where('score', 'in', [1, 2])->count();
        $type_num['all_num']   = $type_num['very_good'] + $type_num['general'] + $type_num['rubbish'];
        //好评率
        @$goods_ratio = $type_num['very_good'] / $type_num['all_num'];
        $goods_ratio = ((number_format($goods_ratio, 2)) * 100) . "%"; //保留两位小数

        try {
            $trans                 = $this->transform($list);
            $list['img']           = $trans['img'];
            $list['add_time']      = $trans['add_time'];
            $list['goods_img']     = $trans['goods_img'];
            $list['nick_name']     = $trans['nick_name'];
            $list['head_portrait'] = $trans['head_portrait'];
            //查询店家回复
            $reply = db('goods_comment_reply')->where(['cid' => $list['id'], 'reply_type' => 2])->field('comment,add_time')->select();
            if ($reply) {
                $list['store_reply'] = $reply;
            }
        } catch (\Exception $e) {
            
        }
        
        $list['type_num']    = $type_num; //商品类型数量
        $list['goods_ratio'] = $goods_ratio; //好评率
        return api_json_echo(true, '成功', $list, 200);
    }
    /**
     * 返回值转化
     */
    private function transform($data)
    {
        //图片转化
        $img = json_decode($data['img']) ?: [];
        foreach ($img as $im_k => $im_v) {
            $im_v       = zy_domain() . $im_v;
            $img[$im_k] = $im_v;
        }
        $data['img'] = $img;
        //时间转化
        $data['add_time'] = date('Y-m-d H:i:s', $data['add_time']);
        //商品图转化
        if (!empty($data['goods_img'])) {
            // $data['goods_img'] = zy_domain() . '/plugins/goods/view/image/' . $data['goods_img'];
            $data['goods_img'] = zy_domain() . $data['goods_img'];
        }

        //判断是否匿名
        if ($data['is_anonym'] == 1) {
            $anon                  = new GoodsCommentModel();
            $data['nick_name']     = $anon->anonym($data['nick_name']);
            $data['head_portrait'] = zy_domain() . '/' . $this->head; //默认头像
        } else {
            $data['head_portrait'] = zy_domain() . $data['head_portrait']; //默认头像
        }
        return $data;
    }
    /**
     * 查看评论
     * @param  $id        评论id
     */
    public function commentDetails()
    {
        $param = $this->request->post();
        if (empty($param['id'])) {
            return api_json_echo(false, '未传id', '', 100);
        }
        $data                  = db('goods_comment')->where('id', $param['id'])->find();
        $trans                 = $this->transform($data);
        $data['img']           = $trans['img'];
        $data['add_time']      = $trans['add_time'];
        $data['goods_img']     = $trans['goods_img'];
        $data['nick_name']     = $trans['nick_name'];
        $data['head_portrait'] = $trans['head_portrait'];
        $data['reply_list']    = db('goods_comment_reply')->where('cid', $param['id'])->select();
        return api_json_echo(true, '成功', $data, 200);
    }
    /**
     * 评论隐藏删除
     * @param  $id         评论id
     * @param  $uid        用户id
     */
    public function hideComment()
    {
        $param = $this->request->post();
        $uid   = $this->uid;
        if (empty($param['id'])) {
            return api_json_echo(false, '未传id', '', 101);
        }
        $data = db('goods_comment')->where(['id' => $param['id'], 'uid' => $uid])->update(['is_hide' => 1]);
        if (empty($data)) {
            return api_json_echo(false, '未找到匹配的评论', 102);
        }
        return api_json_echo(true, '成功', '', 200);
    }
    /**
     *删除自己写的回复
     * @param  $uid        用户id
     * @param  $id        回复id
     */
    public function deleteReply($isModule = false)
    {
        $param = $this->request->post();
        $uid   = $this->uid;
        if (empty($param['id'])) {
            return api_json_echo(false, '未传id', '', 101);
        }
        $data = db('goods_comment_reply')->where(['id' => $param['id'], 'uid' => $uid])->delete();
        if (!$data) {
            return api_json_echo(false, '失败', '', 102);
        }
        return api_json_echo(true, '成功', '', 200);
    }
    /**
     * 我的全部评论
     * @param  $uid        用户id
     */
    public function myComment()
    {
        $param = $this->request->post();
        checkParam(['pageNum', 'page'], $param);
        $anon = new GoodsCommentModel();
        $uid  = $this->uid;
        $data = db('goods_comment')->where(['uid' => $uid, 'is_hide' => 0])->order('add_time', 'desc')->paginate($param['pageNum'], false, ['page' => $param['page']]);
        foreach ($data as $key => $value) {
            $trans                  = $this->transform($value);
            $value['img']           = $trans['img'];
            $value['add_time']      = $trans['add_time'];
            $value['goods_img']     = $trans['goods_img'];
            $value['nick_name']     = $trans['nick_name'];
            $value['head_portrait'] = $trans['head_portrait'];
            $data[$key]             = $value;
        }
        return api_json_echo(true, '成功', $data, 200);
    }
    /**
     * 举报
     * @param  $id        评论id
     */
    public function report()
    {
        $param = $this->request->post();
        $data  = db('goods_comment')->where(['id' => $param['id']])->setInc('report');
        if (!$data) {
            return api_json_echo(false, '请传有效评论id', '', 100);
        }
        return api_json_echo(true, '平台正在受理', '', 200);
    }
    /**
     * BASE64保存并返回路径
     */
    private function saveBase64Image($modular = '', $image_path = 'img', $base64_image_content)
    {
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)) {
            //图片后缀
            $type = $result[2];
            //保存位置--图片名
            $image_name      = date('YmdHis') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT) . "." . $type;
            // $image_file_path = "/plugins/" . $modular . "/view/public/image/" . $image_path;
            $image_file_path = "/upload/" . $modular ;//upload下
            $image_file      = ROOT_PATH . 'public' . $image_file_path;
            $imge_real_url   = $image_file . '/' . $image_name;
            $imge_web_url    = $image_file_path . '/' . $image_name;
            if (!file_exists($image_file)) {
                mkdir($image_file, 0700);
                fopen($image_file . '\\' . $image_name, "w");
            }
            //解码
            $decode = base64_decode(str_replace($result[1], '', $base64_image_content));
            if (file_put_contents($imge_real_url, $decode)) {
                $data['code']      = 0;
                $data['imageName'] = $image_name;
                $data['url']       = $imge_web_url; //'https://'.$_SERVER['HTTP_HOST'].
                $data['msg']       = '保存成功！';
            } else {
                $data['code']       = 1;
                $data['imgageName'] = '';
                $data['url']        = '';
                $data['msg']        = '图片保存失败！';
            }
        } else {
            $data['code']       = 1;
            $data['imgageName'] = '';
            $data['url']        = '';
            $data['msg']        = 'base64图片格式有误！';
        }
        return $data;
    }
    /**
     * 查询是否评论
     * @param  $goodsid    商品id
     * @param  $uid        用户id
     * @param  $orderid    订单id
     */
    public function isComment($uid, $orderid, $goodsid = false)
    {
        $param = $this->request->post();
        if (empty($param['goodsid']) || empty($param['orderid'])) {
            return api_json_echo(false, '缺少参数', '', 100);
        }
        $uid     = $this->uid;
        $goodsid = $param['goodsid'];
        $orderid = $param['orderid'];
        $data    = db('goods_comment')->where(['uid' => $uid, 'goods_id' => $goodsid, 'order_id' => $orderid])->find();
        if (!$data) {
            return api_json_echo(true, '未评论', 1, 200);
        }
        return api_json_echo(true, '已评论', 2, 200);
    }
}
